require "Common/define"
require "Logic/Config"
require "Common/functions"
local PlayerInfo=require("View/UIRanking/PlayerInfo")


UIRanking = UIBase.New(PanelResNames.UIRanking)
local t = UIRanking


function t.Init(pageIndex)
     t.pageIndex = pageIndex or 3
    UIBase.Init(t);
end

function t:OnCreate()
    self:RegisterEvent(Config.EventType.RefreshRankList,self.ResNoticeSelfRankMsg,self)
    self:RegisterEvent(Config.EventType.RefreshSpeak,self.RefreshSpeak,self)
    self:RegisterEvent(Config.EventType.RefreGivePrais,self.RefreshGive,self)
    
    self.spineSprine = {};
    self.drawWrappers = {};
    self.playerInfoList={};
    self.playerSpeakList={};
    self.playerFrameList = {};
    self.v={};
    self.playerspeak=self:GetController("playerspeak");
    self.backBtn=self:GetChild("BackButton");
    self.btn_sort=self:GetChild("btn_sort");
    self.btn_say=self:GetChild("btn_say");
    self.RankingTips1=self:GetChild("RankingTips1");
    self.RankingTips2=self:GetChild("RankingTips2");
    self.ctrlShowTips=self:GetController("Show");
    self.btn_award = self:GetChild("btn_Award")
    local btn_award_title = self.btn_award:GetChild("title")
    btn_award_title.text = getLanguage("UIRanking07")
    
    self.txt_award_time = self.btn_award:GetChild("Time")

    self.txt_title = self:GetChild("title"):GetChild("title");
    self.txt_title.text = getLanguage("UIRanking")
    self.utimer=nil;
    
    self.v=decodeJsonStrToTabel( G.dataTable["t_global"]["308"]["f_string_value"]);
    self.mydata = logicMgr.NoticeManager.selfInfo;
    local my=self:GetChild("Com_YourRank");
    self.rank=my:GetController("rank");
    self.ctrlNoRank=my:GetController("ctrlNoRank");
    self.myname=my:GetChild("name");
    self.mylevel=my:GetChild("level");
    self.myrank=my:GetChild("rank");
    self.fight=my:GetChild("fight");
    self.myhead=my:GetChild("head"):GetChild("head"):GetChild("HeadIcon");
    self.myframeIcon = my:GetChild("head"):GetChild("frame");
  
    for i = 1, 5 do
         ---@type Billboard_BlessPanel
         local info = self:CreateComponent(PlayerInfo,self:GetChild("playerInfo" .. i),i)          
         table.insert(self.playerInfoList, info);         
     end
     self.playerlist = {};
     for i = 1, 5 do
         table.insert(self.playerlist, self:GetChild("player"..i));
     end
     for i = 1, 5 do
        table.insert(self.playerSpeakList, self:GetChild("player"..i.."speak02"));
    end
    
    self:RegisterOnClick(self.backBtn, self.onClose)
    self:RegisterOnClick(self.btn_sort, self.OpenRanklist)
    self:RegisterOnClick(self.btn_say, self.SendSpeak)
    self:RegisterOnClick(self.btn_award, self.onClickAward)
    --NoticeHandler.ReqEditMsg("123"); 
end

function t:RefreshBalanceData()
    local server_time = Config.serverTime/1000 
    local end_time = logicMgr.NoticeManager.rank_balance_time
    local dis_time =  end_time - server_time
    self:CloseTimer()
    if dis_time > 0 then
        self.btn_award.visible = true
        self.txt_award_time.text = string.format(getLanguage("UIRanking11"), getTimeStrD_H_M_S(dis_time) ) 
        self.activity_time_id = utimer.timeCall(function() 
            dis_time = dis_time -1
            local tips_str = string.format(getLanguage("UIRanking11"), getTimeStrD_H_M_S(dis_time))
            if self.banner_tips_str == nil or self.banner_tips_str ~= tips_str then
                if self.txt_award_time then
                    self.txt_award_time.text =  tips_str
                    self.banner_tips_str = tips_str
                end
            end
            
            if dis_time <= 0 then 
                if self.txt_award_time then
                    self.txt_award_time.text = getLanguage("Sys_ActivityEnd")
                end
                self:CloseTimer()
                if self.btn_award ~= nil then
                    self.btn_award.visible = false
                end
            end
        end, 1000, dis_time) 
    else
        if self.btn_award ~= nil then
            self.btn_award.visible = false
        end
    end
end

function t:CloseTimer()
    if self.activity_time_id ~= nil then
        utimer.remove(self.activity_time_id)
        self.activity_time_id = nil 
    end
end

function t:RefreshMy()
    if logicMgr.NoticeManager.myRank<=50 then
        self.ctrlNoRank.selectedIndex=0;
        self.rank.selectedIndex=3;
        self.myrank.text=logicMgr.NoticeManager.myRank;
    else
        self.ctrlNoRank.selectedIndex=1;
    end
    self.mylevel.text=self.mydata.playerShowInfo.level;
    self.fight.text=getNumString(logicMgr.HeroManager.GetHerosSumPower())
    self.myname.text=self.mydata.playerShowInfo.name;
    self.myhead.url= logicMgr.SkinManager.GetHeroIconBySkinId(logicMgr.HeroManager.GetRoleInfo("pic")); --"ui://ICONAtlas/"..
    self.myframeIcon.url = "ui://ICONAtlas/" .. logicMgr.HeroManager.GetRoleHeadFrame();
end

function t:OpenRanklist()
    showUI(PanelNames.UIRankFight);
end

function t:SendSpeak()
    showUI(PanelNames.UIRankingSpeak)
end

function t:onClickAward()
    showUI(PanelNames.UIRankingShow)
end

function t:onClose()
    self.isClose = nil;
    for k,v in pairs(self.spineSprine) do
        v:GetComponent("SkeletonGraphic").material:SetFloat("_StencilComp", 8);
    end
    closeUI(PanelResNames.UIRanking);
end

function t:OnDestroy()
    HelperFunc.UnloadLihui()
    self:CloseTimer()
    UIRedDots.removeViewEvent(PanelResNames.UIRanking)
end
function t:ReAllfresh()
    self.PlayerRankList = nil
    self.PlayerRankList=logicMgr.NoticeManager.PlayerRankList;

    -- if logicMgr.NoticeManager.myRank<=5 then
    --     self.btn_say.visible=true;
    -- else
    --     self.btn_say.visible=false;
    -- end
    self.RankingTips1.text=string.format(getLanguage("UIRanking01"), 5-logicMgr.NoticeManager.dayClick);

    if logicMgr.NoticeManager.sumClick >= 100 then
        self.RankingTips2.text = ""
        self.ctrlShowTips.selectedIndex = 1
    else
        self.RankingTips2.text=string.format(getLanguage("UIRanking02"), logicMgr.NoticeManager.sumClick,100);
        self.ctrlShowTips.selectedIndex = 0
    end
    if self.PlayerRankList == nil or next(self.PlayerRankList) == nil and not self.isClose then
        self.isClose = true;
        HelperFunc.CloseUILoading()
    end
    local enemyNum = 0;
    for i = 1, 5 do--加载立绘
        if self.PlayerRankList[i]==nil or self.PlayerRankList[i].playerShowInfo == nil then
            break;
        end
        enemyNum = enemyNum + 1;
        --如果自己上榜了，展示自己的英雄皮肤（暂时忽略其他人的皮肤显示）
        --local skinId = nil
        --if logicMgr.NoticeManager.myRank <= 5 then
        --    skinId = logicMgr.SkinManager.getHeroSkinId(tonumber(self.PlayerRankList[i].playerShowInfo.pic))
        --end
        local imageName = logicMgr.SkinManager.GetHeroDrawPathBySkinId(self.PlayerRankList[i].playerShowInfo.pic)
        resMgr:LoadModelPrefab(imageName,function(go)
           if (self.drawWrappers[i] == nil) then
               self.drawWrappers[i] = GoWrapper.New();
           end
           if self.spineSprine[i] ~= nil then
                destroyImmediate(self.spineSprine[i])
                self.spineSprine[i] = nil
            end
           self.spineSprine[i] = newObject(go);
           self.spineSprine[i].name = imageName;--"objHeroDraw"..i;
           self.spineSprine[i]:AddComponent(TCanvas);
           if self.spineIsIning then
               self.spineSprine[i]:GetComponent("SkeletonGraphic"):SetSkenColor(Color.New(1, 1, 1, 0));
           else
               self.spineSprine[i]:GetComponent("SkeletonGraphic"):SetSkenColor(Color.New(1, 1, 1, 1));
           end
           self.drawWrappers[i]:SetWrapTarget(self.spineSprine[i], false);
           -- Util.Lua_SetLocalPositionXYZ(this.spineSprine[i].transform, v[4], v[5], 0)
           local scale,location,offset = logicMgr.SkinManager.GetSkinRankSize(self.PlayerRankList[i].playerShowInfo.pic)

            if i == 2 or i ==4 then
                Util.Lua_SetLocalScaleXYZ(self.spineSprine[i].transform, self.v[i]*scale[1]/100.0, self.v[i]*scale[2]/100.0, self.v[i]/100.0)   
            else
                Util.Lua_SetLocalScaleXYZ(self.spineSprine[i].transform, -self.v[i]*scale[1]/100.0, self.v[i]*scale[2]/100.0, self.v[i]/100.0)           
            end
            if offset == nil or #offset ~= 5 then
                Util.Lua_SetLocalPositionXYZ(self.spineSprine[i].transform, location[1], location[2], 0)  
            else
                Util.Lua_SetLocalPositionXYZ(self.spineSprine[i].transform, location[1]+offset[i][1], location[2]+offset[i][2], 0)  
            end
            local gragh = self.playerlist[i]:GetChild("player")
            gragh:SetNativeObject(self.drawWrappers[i]);
            if self.spineSprine[i]:GetComponent("SkeletonGraphic") then
                self.spineSprine[i]:GetComponent("SkeletonGraphic").AnimationState:SetAnimation(0, "idle1", true);
            end
            enemyNum = enemyNum - 1;
            if enemyNum <= 0 then
                utimer.timeCall(HelperFunc.CloseUILoading, 300, 1);
            end
            self.spineSprine[i]:GetComponent("SkeletonGraphic").material:SetFloat("_StencilComp", 3);
            self.spineSprine[i]:GetComponent("SkeletonGraphic").material:SetFloat("_Stencil",1);
        end)
    end
    for i = 1, 5 do
        self.playerInfoList[i]:InitData(self.PlayerRankList[i]);
    end

    for i = 1, 5 do
        if self.PlayerRankList[i]==nil then
            break;
        end
        if self.PlayerRankList[i].extend2 then
            self.playerSpeakList[i].text = self.PlayerRankList[i].extend2
        else
            self.playerSpeakList[i].text = getLanguage("UIRanking03")
        end
    end
end
function t:RefreshGive(playerId)
    for i = 1, #self.PlayerRankList do
        if self.PlayerRankList[i].playerShowInfo.playerId==playerId then
            self.playerInfoList[i]:InitData(self.PlayerRankList[i]);
            self.RankingTips1.text=string.format(getLanguage("UIRanking01"), 5-logicMgr.NoticeManager.dayClick);
            if logicMgr.NoticeManager.sumClick >= 100 then
                self.ctrlShowTips.selectedIndex = 1
            else
                self.ctrlShowTips.selectedIndex = 0
                self.RankingTips2.text=string.format(getLanguage("UIRanking02"), logicMgr.NoticeManager.sumClick,100);
            end
            return;
        end
    end
  
end

function t:RefreshSpeak(msg)
    self.playerSpeakList[logicMgr.NoticeManager.myRank].text=msg
    self.playerspeak.selectedIndex=logicMgr.NoticeManager.myRank-1;
    if self.utimer then
        utimer.remove(self.utimer)
        self.utimer=utimer.timeCall(self.RefreshPlayerSpeak,2000,-1,self);
    end
end

--更新个人宣言
function t:RefreshPlayerSpeak()
    local n=math.random(0,4);
    self.playerspeak:SetSelectedIndex(n);
end

function t:OnEnable()
    self.playerspeak.selectedIndex=0
    NoticeHandler.ReqRTFightRank();
    self:ReAllfresh();

    --  self.utimer=utimer.timeCall(self.RefreshPlayerSpeak,2000,-1,self);
end
function t:ResNoticeSelfRankMsg()

    self:ReAllfresh();
    self:RefreshMy()
    self:RefreshBalanceData()
end

function t:OnDisable()
    if self.utimer then
        utimer.remove(self.utimer)
    end
    self:CloseTimer()
    for key, value in pairs(self.spineSprine) do
        destroyImmediate(value)
    end
    self.spineSprine = {};
    
    for key, value in pairs(self.drawWrappers) do
        if not HelperFunc.IsNull(value) then
            value:Dispose()
        end
    end
    self.drawWrappers = {};

    --HelperFunc.UnloadUnusedAssets(EnumConst.ClearType.Prefab)
end

return t;